package org.x.yuenovel.util;

import com.alibaba.fastjson.JSON;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ses.v20201002.SesClient;
import com.tencentcloudapi.ses.v20201002.models.SendEmailRequest;
import com.tencentcloudapi.ses.v20201002.models.SendEmailResponse;
import com.tencentcloudapi.ses.v20201002.models.Template;
import com.wf.captcha.SpecCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.x.yuenovel.contants.CommonConstant;
import org.x.yuenovel.enums.EmailTemplateEnum;
import org.x.yuenovel.enums.ResultCodeEnum;
import org.x.yuenovel.exception.ApiException;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xuezhendong
 * @date 2022/4/23 12:17 下午
 */
@Component
@Slf4j
public class EmailUtil {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${email.secretId:}")
    private String secretId;

    @Value("${email.secretKey:}")
    private String secretKey;

    /**
     * 发送邮箱验证码，30分钟有效
     * @param email email
     */
    public void senEmailCaptcha4Register(String email) {
        if (!ObjectUtils.isEmpty(stringRedisTemplate.opsForValue().get(email))) {
            throw new ApiException(ResultCodeEnum.EMAIL_CAPTCHA_SENDED);
        }
        SpecCaptcha specCaptcha = new SpecCaptcha(0, 0, 5);
        String code = specCaptcha.text();
        Map<String, String> param = new HashMap<>();
        param.put("code", code);
        stringRedisTemplate.opsForValue().set(email, code, CommonConstant.EMAIL_CAPTCHA_DURATION, TimeUnit.MINUTES);
        if(ObjectUtils.isEmpty(secretId) || ObjectUtils.isEmpty(secretKey)){
            log.info("ak sk为空，模拟发送邮件成功，验证码：{}", code);
        }else{
            send(email, EmailTemplateEnum.REGISTE, JSON.toJSONString(param));
        }
    }

    private void send(String mail, EmailTemplateEnum templateEnum, String message) {
        if (ObjectUtils.isEmpty(message) || templateEnum == null) {
            log.error("发送邮件参数为空");
            return;
        }
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint(CommonConstant.EMAIL_HOST);
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendEmailRequest req = new SendEmailRequest();
            req.setFromEmailAddress(CommonConstant.EMAIL_FROM_ADDRESS);

            String[] destination1 = {mail};
            req.setDestination(destination1);

            Template template1 = new Template();
            template1.setTemplateID(templateEnum.getTemplateId());
            template1.setTemplateData(message);
            req.setTemplate(template1);

            req.setSubject(templateEnum.getSubject());
            // 返回的resp是一个SendEmailResponse的实例，与请求对象对应
            SendEmailResponse resp = client.SendEmail(req);
            // 输出json格式的字符串回包
            log.info("发送邮件成功：{}", SendEmailResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error("发送邮件失败：{}", e.toString());
        }
    }
}
